package com.eqdd.yiqidian.ui.yiqixue.fragment;

import android.databinding.DataBindingUtil;
import android.databinding.ViewDataBinding;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.text.InputType;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;

import com.afollestad.materialdialogs.MaterialDialog;
import com.eqdd.yiqidian.CoolRefreshRecyclerViewFragmentCustom;
import com.eqdd.yiqidian.R;
import com.eqdd.yiqidian.adapter.recycleadapter.ItemClickSupport;
import com.eqdd.yiqidian.adapter.slimadapter.SlimAdapterEx;
import com.eqdd.yiqidian.adapter.slimadapter.SlimInjector;
import com.eqdd.yiqidian.adapter.slimadapter.viewinjector.IViewInjector;
import com.eqdd.yiqidian.base.BaseActivity;
import com.eqdd.yiqidian.base.BaseFragment;
import com.eqdd.yiqidian.base.Config;
import com.eqdd.yiqidian.bean.rebuild.LearnPhotoMenuListBean;
import com.eqdd.yiqidian.bean.rebuild.HttpResultRows;
import com.eqdd.yiqidian.helper.mvchelper.ModelRx2DataSource;
import com.eqdd.yiqidian.helper.mvchelper.Rx2DataSource;
import com.eqdd.yiqidian.http.HttpConfig;
import com.eqdd.yiqidian.http.HttpResult;
import com.eqdd.yiqidian.http.JsonConverter;
import com.eqdd.yiqidian.ui.yiqixue.LearnPhotoActivity;
import com.eqdd.yiqidian.utils.BottomSheetUtil;
import com.eqdd.yiqidian.utils.HttpUtil;
import com.eqdd.yiqidian.utils.ToastUtil;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.model.Response;
import com.lzy.okrx2.adapter.FlowableBody;
import com.shizhefei.mvc.MVCCoolHelper;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Flowable;

/**
 * @author吕志豪 .
 * @date 18-2-7  下午2:12.
 * Github :https://github.com/lvzhihao100
 * E-Mail：1030753080@qq.com
 * 简书 :http://www.jianshu.com/u/6e525b929aac
 */

public class FindPhotoFragment extends BaseFragment {
    private CoolRefreshRecyclerViewFragmentCustom dataBinding;
    private int pageNum;
    private SlimAdapterEx<LearnPhotoMenuListBean> slimAdapterEx;
    private MVCCoolHelper<List<LearnPhotoMenuListBean>> mvcHelper;
    private int currentPos;
    private BottomSheetDialog optionChoose;
    private BottomSheetDialog deleteChoose;

    @Override
    public ViewDataBinding initBinding(LayoutInflater inflater) {
        return dataBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_cool_recycler_view, null, false);
    }

    @Override
    protected void initData() {
        if (slimAdapterEx == null) {
            String url = getArguments().getString(Config.URL);
            String lectureGuid = getArguments().getString(Config.LECTURE_GUID);
            dataBinding.recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            //添加自定义分割线
            DividerItemDecoration divider = new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
            dataBinding.recyclerView.addItemDecoration(divider);
            slimAdapterEx = SlimAdapterEx.create().register(R.layout.list_item_26, new SlimInjector<LearnPhotoMenuListBean>() {
                @Override
                public void onInject(LearnPhotoMenuListBean data, IViewInjector injector) {

                    injector.imageCircle(R.id.iv_head, data.getImageUrl())
                            .text(R.id.tv_upper_content, data.getTitle())
                            .text(R.id.tv_down_content, data.getImageCount() + "张");
                }
            }).attachTo(dataBinding.recyclerView).updateData(new ArrayList());
            ItemClickSupport.addTo(dataBinding.recyclerView)
                    .setOnItemClickListener((recyclerView, position, v) -> {
                        Bundle bundle = new Bundle();
                        bundle.putInt(Config.ID, slimAdapterEx.getDataItem(position).getId());
                        bundle.putString(Config.TITLE, slimAdapterEx.getDataItem(position).getTitle());
                        startActivity(LearnPhotoActivity.class, bundle);
                    })
                    .setOnItemLongClickListener((recyclerView, position, v) -> {
                        currentPos = position;
                        deletePhotoMenu();
                        return true;
                    });
            ModelRx2DataSource<LearnPhotoMenuListBean> dataSource = new ModelRx2DataSource<>(new ModelRx2DataSource.OnLoadSource() {
                @Override
                public Flowable<List> loadSource(int page, Rx2DataSource.DoneActionRegister register) {
                    pageNum = page == 1 ? 0 : pageNum;
                    return OkGo.<HttpResultRows<LearnPhotoMenuListBean>>post(HttpConfig.BASE_URL + url)
                            .params("page", pageNum)
                            .params("lectureGuid", lectureGuid)
                            .converter(new JsonConverter<HttpResultRows<LearnPhotoMenuListBean>>() {
                                @Override
                                public void test() {
                                    super.test();
                                }
                            }).adapt(new FlowableBody<>())
                            .flatMap(listResultBean -> {
                                pageNum = listResultBean.getItems().getPage();
                                if (listResultBean.getStatus() == 200) {
                                    return Flowable.just(listResultBean.getItems() == null ? new ArrayList<LearnPhotoMenuListBean>() : listResultBean.getItems().getRows());
                                } else {
                                    ToastUtil.showShort(listResultBean.getMsg());
                                    return Flowable.just(new ArrayList<>());
                                }
                            });
                }
            });
            mvcHelper = new MVCCoolHelper<>(dataBinding.coolRefreshView);
            mvcHelper.setDataSource(dataSource);
            mvcHelper.setAdapter(slimAdapterEx);
            mvcHelper.refresh();
        }
    }

    private void deletePhotoMenu() {
        if (optionChoose == null) {
            optionChoose = BottomSheetUtil.getBottomSheet(getActivity(), null, (recyclerView, position, v) -> {
                optionChoose.hide();
                if (position == 1) {
                    deleteChoose = BottomSheetUtil.getBottomSheet(getActivity(), "确认删除[" + slimAdapterEx.getDataItem(currentPos).getTitle() + "]相册?\n删除之后,该相册里面的照片也会被相应的删除",
                            (recyclerView1, position1, v1) -> {
                                deleteChoose.hide();
                                HttpUtil.deleteLearnPhotoMenu((BaseActivity) getActivity(), slimAdapterEx.getDataItem(currentPos).getId(), () -> {
                                    slimAdapterEx.getData().remove(currentPos);
                                    slimAdapterEx.notifyItemRemoved(currentPos);
                                });
                            }, "删除");
                    deleteChoose.show();
                }
                if (position == 0) {
                    new MaterialDialog.Builder(getActivity())
                            .title("请输入相册名字")
                            .inputType(InputType.TYPE_CLASS_TEXT)//可以输入的类型-电话号码
                            .input("请输入相册名字", slimAdapterEx.getDataItem(currentPos).getTitle(), (dialog, input) -> Log.i("yqy", "输入的是：" + input))
                            .onPositive((dialog, which) -> {
                                if (dialog.getInputEditText().length() > 0) {
                                    HttpUtil.updateLearnPhotoMenuName((BaseActivity) getActivity(), slimAdapterEx.getDataItem(currentPos).getId(), dialog.getInputEditText().getText().toString(), () -> {
                                        slimAdapterEx.getDataItem(currentPos).setTitle(dialog.getInputEditText().getText().toString());
                                        slimAdapterEx.notifyItemChanged(currentPos);
                                    });
                                }
                            }).show();
                }

            }, "修改相册名字", "删除相册");
        }
        optionChoose.show();

    }

    @Override
    protected void setView() {

    }

    @Override
    public void onClick(View v) {

    }

    public void refresh() {
        mvcHelper.refresh();
    }

}
